package com.example.http.two

import com.example.http.SSLSocketFactoryUtil
import com.example.http.app.appContext
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File

class RetrofitManager {
    //okhttp的缓存 100M
    var cache: Cache = Cache(File("${appContext.externalCacheDir?.path}/okhttp_cache/"), 100 * 1024 * 1024)
    //半生对象 静态
    companion object{
        //懒汉单例双重教研锁
        private var instance:RetrofitManager?=null
        fun getInstance():RetrofitManager{
            if (instance==null){
                synchronized(RetrofitManager::class.java){
                    if (instance==null){
                        instance=RetrofitManager()
                    }
                }

            }
            return instance!!
        }
    }
    private fun getRetrofit(): Retrofit {
        val retrofit = Retrofit.Builder()
            .baseUrl("http://test-zsjc-openapi.qimoyun.com")
            .client(getOkhttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return  retrofit

    }

    private fun getOkhttpClient(): OkHttpClient {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        //判断是否debug模式下
        httpLoggingInterceptor.level= HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .addInterceptor(HttpMallHeaderInterceptor())//自定义请求头拦截器
            .addInterceptor(httpLoggingInterceptor)
            .retryOnConnectionFailure(true)//失败重连
            .cache(cache)//缓存
            .sslSocketFactory(//https证书认证
                SSLSocketFactoryUtil.createSSLSocketFactory(),
                SSLSocketFactoryUtil.createTrustAllManager()
            )
            .hostnameVerifier(SSLSocketFactoryUtil.TrustAllHostnameVerifier())//域名认证
            .build()
    }

    fun <T> create(service:Class<T>):T{
        return getRetrofit().create(service)
    }
}